import { request, getImageUrl } from '/utils'
Component({
    props: {
        alipayTradeNo: null,
        style: ''
    },
    data: {
        cartList: [],
        cartListStock: 0,
        cartListTotalPrice: '0.00',
        cartListTotalOriginalPrice: '0.00'
    },
    didMount() {
        this.getCartList();
    },
    methods: {
        async getCartList() {
            let code, cartList = [],
                { alipayTradeNo } = this.props;
            // const { code, data: cartList } = await request.get('/miniapp/shoppingCart/getCartList');
            if (alipayTradeNo) {
                const res = await request.get('/miniapp/order/detail', { params: { alipayTradeNo } });
                code = res.code;
                cartList = res.data.orderItems;
            } else {
                const res = await request.get('/miniapp/shoppingCart/getCartList');
                code = res.code;
                cartList = res.data;
            }
            if (code !== 200) return;
            const cartListStock = cartList.reduce((pre, item) => pre + item.amount, 0);
            const cartListTotalPrice = (cartList.reduce((pre, item) => pre + item.sku.price * item.amount, 0) / 100).toFixed(2);
            const cartListTotalOriginalPrice = (cartList.reduce((pre, item) => pre + item.sku.originalPrice * item.amount, 0) /
                    100)
                .toFixed(2);
            this.setData({
                cartList: cartList.map(({ goods, sku, ...item }) => ({
                    ...item,
                    goods: {
                        ...goods,
                        cover: getImageUrl(goods
                            .cover)
                    },
                    sku: {
                        ...sku,
                        images: sku.images.map(item => getImageUrl(item)),
                        price: (sku.price * item
                            .amount / 100).toFixed(2),
                        originalPrice: (sku.originalPrice * item.amount / 100)
                            .toFixed(2)
                    }
                })),
                cartListStock,
                cartListTotalPrice,
                cartListTotalOriginalPrice
            });
        },
    }
});